package com.transaction.aop;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.TransactionStatus;

@Slf4j
@Aspect
@Component
public class MyTransactionAop {

    @Autowired
    private MyTransaction myTransaction;
    @Around(value = "@annotation(com.transaction.annotation.MyTransactionAnnotation)")
    public Object myTransactionAop(ProceedingJoinPoint joinPoint){

        log.info("进入到事务aop, 准备开启事务");
        TransactionStatus transactionStatus = myTransaction.begin();

        try {
            log.info("准备执行目标方法");
            // 执行目标方法
            Object object = joinPoint.proceed();

            log.info("目标方法执行完毕，准备提交");

            // 执行方法完毕，提交事务，并返回
            myTransaction.commit(transactionStatus);
            return object;
        }catch (Throwable throwable) {

            log.error("目标函数异常，手动回滚");
            // 目标函数异常，手动回滚
            myTransaction.rollback(transactionStatus);
            return "目标函数异常";
        }
    }
}
